package calao.client.ui;

import java.util.HashMap;
import java.util.Vector;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class ActionListBox
extends ListBox
implements ClickListener
{
	
	static class Options
	{
		boolean reverseLoop;
	}
	
	final Vector actionButtons = new Vector();
	final HashMap optionsMap = new HashMap();
	
	public ActionListBox()
	{
		super(true);
		addChangeListener(new ChangeListener() {
			public void onChange(Widget sender) {
				if (getSelectedIndex()!=-1) {
					allowActions(true);
					onSelection();
				}
				else {
					allowActions(false);
				}
			}
		});
	}
	
	public void addActionButton(Button button)
	{
		actionButtons.add(button);
		button.addClickListener(this);
		if (getSelectedIndex()==-1) button.setEnabled(false);
	}
	
	protected void onAction(Button button, int index) { }
	
	protected void onSelection() { }

	public void onClick(Widget sender) 
	{
		if (actionButtons.contains(sender))	{
			Options opts = (Options)optionsMap.get(sender);
			if (opts!=null && opts.reverseLoop) {
				for (int i=getItemCount()-1; i>=0; i--) {
					if (isItemSelected(i)) onAction((Button)sender, i);
				}
			}
			else {
				for (int i=0; i<getItemCount(); i++) {
					if (isItemSelected(i)) onAction((Button)sender, i);
				}				
			}
		}
	}
	
	public void setAllSelected(boolean selected)
	{
		for (int i=0; i<getItemCount(); i++) {
			setItemSelected(i, selected);
		}
		allowActions(selected);
	}
	
	private void allowActions(boolean allowed)
	{
		for (int i=0; i<actionButtons.size(); i++) {
			((Button)actionButtons.get(i)).setEnabled(allowed);
		}		
	}
	
	public void moveItem(int index, int offset)
	{
		int newIndex = offset+index;
		if (newIndex<0) newIndex = 0;
		if (newIndex>=getItemCount()) newIndex = getItemCount()-1;
		if (newIndex!=index) {
			String text = getItemText(index);
			String value = getValue(index);
			boolean selected = isItemSelected(index);
			removeItem(index);
			insertItem(text, value, newIndex);
			setItemSelected(newIndex, selected);
		}
	}
	
	public void setOptions(Button button, boolean reverseLoop)
	{
		Options opts = new Options();
		opts.reverseLoop = reverseLoop;
		optionsMap.put(button, opts);
	}

}
